import React, { PureComponent } from 'react';
import _ from 'lodash';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Select, Input, Checkbox, Tooltip, Spin, message } from 'antd';
import { PrimaryGhostC, FirstHeaderC, SecondHeaderC, UploadC, FormGroup, AdvancedSearch, FixedButtonC, NormalCardC, IconC, SingleDateC, PrimaryC } from '../../../comps';
const FormItem = Form.Item;
import { connect } from 'dva';
import moment from 'moment';
import myStyle from './style.less';
import accounting from 'accounting';
import CardContent from './cardContent';
import ValuateAnalysisInfoTable from './valuateAnalysisInfoTable';
const { TextArea } = Input;
@Form.create()
@connect(({ qualificationManagementPlanMaintenanceM, loading, userM: user }) => ({ qualificationManagementPlanMaintenanceM, loading, user }))
export default class ValuateAnalysisInfo extends PureComponent {
  static defaultProps = {
    type: 1, //1新增，2 查看详情
  };
  constructor(props) {
    super(props);
    this.state = {
      cardOneEdit: false,
      tableData: [],
      columns: [],
      dataSource: [],
      currenttotalrmbmoney: undefined, //总计信息-资管及委外资产当前总折算人民币金额
      currenttotalamount: undefined, //总计信息-资管及委外资产当前总数量
      uninvestposition: undefined, //总计信息-资管及委外资产未投资头寸
      time: moment(new Date()).format('YYYY-MM-DD'),
    };
  }
  componentDidMount() {
    this.getTime();
    this.props?.onRef && this.props?.onRef(this);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  getInfo = () => {
    return {
      analysisList: this.state.tableData.map((x) => {
        const { id, ...data } = x;
        return data;
      }),
      currenttotalrmbmoney: this.state.currenttotalrmbmoney,
      currenttotalamount: this.state.currenttotalamount,
      uninvestposition: this.state.uninvestposition,
    };
  };
  getTime = () => {
    const { id } = this.props;
    this.props.dispatch({
      type: 'qualificationManagementPlanMaintenanceM/getTime',
      payload: {
        id,
      },
      callback: (type, data) => {
        if (type == 'success') {
          if (data?.dataSource) {
            this.setState({ time: data.dataSource });
            // if (this.props.type == 2) {
            this.getTableData({ id: this.props.id, date: data.dataSource });

            // }
          }
        }
      },
    });
  };

  onTimeChange = (e) => {
    this.setState({
      time: e?.format('YYYY-MM-DD'),
    });

    this.getTableData({ id: this.props.id, date: e?.format('YYYY-MM-DD') });
  };

  // 获取表格数据
  getTableData = (params) => {
    this.setState(
      {
        dataSource: undefined,
        currenttotalrmbmoney: undefined, //总计信息-资管及委外资产当前总折算人民币金额
        currenttotalamount: undefined, //总计信息-资管及委外资产当前总数量
        uninvestposition: undefined, //总计信息-资管及委外资产未投资头寸
      },
      () => {
        this.props.dispatch({
          type: 'qualificationManagementPlanMaintenanceM/findanalysis',
          payload: {
            ...(params || {}),
          },
          callback: (type, data) => {
            if (type == 'success') {
              const { columns, dataSource = {} } = data?.data || {};
              this.setState({
                columns: columns,
                dataSource: dataSource?.analysisList?.map((x, index) => {
                  return { ...x, id: index };
                }),
                currenttotalamount: dataSource.currenttotalamount,
                currenttotalrmbmoney: dataSource.currenttotalrmbmoney,
                uninvestposition: dataSource.uninvestposition,
              });
            } else {
              this.setState({
                dataSource: [],
                currenttotalamount: undefined,
                currenttotalrmbmoney: undefined,
                uninvestposition: undefined,
              });
            }
          },
        });
      },
    );
  };

  render() {
    const { currenttotalrmbmoney, currenttotalamount, uninvestposition, columns, dataSource } = this.state;
    return (
      <>
        <SecondHeaderC title='估值解析' />
        <div style={{ display: 'flex' }}>
          <SingleDateC
            form={this.props.form} // form对象
            title='估值日期' // 显示名称
            dataIndex='date' // Form识别的下拉选项Item ID
            onChange={(e) => this.onTimeChange(e)} // 时间变化事件
            initialValue={moment(this.state.time)}
            // disableBegin={moment('2020-01-01')}
            // disableEnd={moment('2020-11-11')}
          />
          {/* <PrimaryC /> */}
          {this.props.type == 1 && (
            <div style={{ paddingTop: '4px' }}>
              <UploadC
                title='文件导入'
                action='gateway/portfolio-server/entrustedinvestment/analysisGzbExcel' //上传地址
                type={1}
                data={{ data: this.state.time }}
                showUploadList={false}
                onUpload={(e) => {
                  if (e?.code == 0) {
                    const { data } = e;
                    const { columns, dataSource = {} } = data || {};

                    this.setState({ dataSource: [] }, () => {
                      this.setState({
                        columns: columns,
                        dataSource: dataSource?.analysisList?.map((x, index) => {
                          return { ...x, id: index };
                        }),
                        currenttotalamount: dataSource.currenttotalamount,
                        currenttotalrmbmoney: dataSource.currenttotalrmbmoney,
                        uninvestposition: dataSource.uninvestposition,
                        // uninvestposition: dataSource.currenttotalamount,: dataSource.currenttotalamount,
                        //                 currenttotalrmbmoney: dataSource.currenttotalamount,
                        //                 uninvestposition: dataSource.currenttotalamount,
                      });
                    });
                  } else if (typeof e == 'string' && e?.indexOf('413 Request Entity Too Large') != -1) {
                    message.error('文件过大');
                  } else {
                    message.error(e?.msg);
                  }
                }}
              />
            </div>
          )}
        </div>
        <div style={{ display: 'flex' }}>
          <NormalCardC
            contentStyle={{ padding: '18px 20px' }}
            Content={
              <CardContent
                value={currenttotalrmbmoney}
                title='资管及委外资产当前总折算人民币金额'
                helper='资管及委外资产在持仓日期当日根据外汇管理局公布的汇率中间价折算成人民币后的总发行金额。'
                precision='2'
                max={999999999999}
                unit='元'
                isEdit={this.props.type == 1}
                onSave={(e) => this.setState({ currenttotalrmbmoney: e })}
              />
            }
            style={{ margin: '10px' }}
            height={'100px'}
          />
          <NormalCardC
            contentStyle={{ padding: '18px 20px' }}
            Content={
              <CardContent
                title='资管及委外资产当前总数量'
                value={currenttotalamount}
                helper='1、如果资管及委外资产为净值型，则该要素报送单位为“份额”；如果资管及委外资产为非净值型，则该要素报送单位为“元”，即持仓当日发行总金额；
                            2、该要素的报送单位应与资产交易登记时买入、卖出资管及委外资产时的“数量”单位保持一致；'
                precision='5'
              />
            }
            style={{ margin: '10px' }}
            height={'100px'}
          />
          <NormalCardC
            contentStyle={{ padding: '18px 20px' }}
            Content={
              <CardContent
                title='资管及委外资产未投资头寸'
                value={uninvestposition}
                helper='现金'
                precision='2'
                max={999999999999}
                unit='元'
                isEdit={this.props.type == 1}
                onSave={(e) => this.setState({ uninvestposition: e })}
              />
            }
            style={{ margin: '10px' }}
            height={'100px'}
          />
        </div>
        <ValuateAnalysisInfoTable
          // tableData
          type={this.props.type}
          columns={columns}
          date={this.state.time}
          dataSource={dataSource}
          onChange={(e) => {
            let amount = undefined;
            if (e?.length > 0) {
              amount = 0;
              e.map((x) => {
                amount += x.bottomPositionNum;
              });
            }
            this.setState({ tableData: e || [], currenttotalamount: amount });
          }}
        />
      </>
    );
  }
}
